#include "dunParser.h"

#define _MAX_ 1024

t_graph 	parserCreate(t_loader		data)
{
	t_graph 							result = NULL;
	char buff[_MAX_], *tmp;
	t_lex lexer = lexerCreate();
	int nbrooms;
	
	loaderGetNextLine(data, buff, _MAX_);
	
	lexerSplit(lexer, buff, " \n");
	
	tmp = lexerGetToken(lexer);
	if (strcmp(tmp, "ROOMS:") == 0)
		nbrooms = lexerGetTokenAsInt(lexer);
	else
	{
		printf("Error at 'Rooms'\n");
		return (NULL);
	}
	free(lexer);
	result = graphCreate(nbrooms+1);
	/*Cheat pour eviter que ca segfault... on a un sommet en trop :/*/
	return (result);
}

void		parserComputeRooms(	t_graph	dun, 
								t_loader	data)
{
	char buff[_MAX_], *tmp;
	int x, y;
	t_lex lexer = lexerCreate();
	

	while ((loaderGetNextLine(data, buff, _MAX_)) 
			&& (strcmp(buff, "ARCS\n") != 0))
	{
		lexerSplit(lexer, buff, " \n");
		tmp = lexerGetToken(lexer);
		if (!strcmp(tmp, "MONSTER:"))
		{
			x = lexerGetTokenAsInt(lexer);
			y = lexerGetTokenAsInt(lexer);
			/*Indiquer que le sommet x a un monstre Lv.y*/
			dun->lsom[x]->room = Monster;
			dun->lsom[x]->value = y;
		}
		
		if (!strcmp(tmp, "BREWERY:"))
		{
			x = lexerGetTokenAsInt(lexer);
			y = lexerGetTokenAsInt(lexer);
			/*Indiquer que le sommet x donne y points de vie*/
			dun->lsom[x]->room = Brewery;
			dun->lsom[x]->value = y * (-1);
		}
		
		if (!strcmp(tmp, "DEAD:"))
		{
			x = lexerGetTokenAsInt(lexer);
			dun->lsom[x]->room = Dead;
			/*Indiquer que le sommet x est un dead-end*/
		}
	}
	free(lexer);
}

void		parserComputeHalls(	t_graph	dun, 
								t_loader	data)
{
	char buff[_MAX_], *tmp;
	int x, y ,z, i;
	t_lex lexer = lexerCreate();
	i = 0;
	while ((loaderGetNextLine(data, buff, _MAX_)) && (buff[0] != '\n'))
	{
		lexerSplit(lexer, buff, " \n");
		tmp = lexerGetToken(lexer);/*ARC:*/

		if (!strcmp(tmp, "ARC:"))
		{
			
			x = lexerGetTokenAsInt(lexer);
			y = lexerGetTokenAsInt(lexer);
			z = lexerGetTokenAsInt(lexer);
			/*On ajoute au sommet x un arc vers z de cout y*/
			graphAddArc(dun, x, z, y);
		}
		else
		{
			free(lexer);
			printf("Error in ARC number %d", i);
			return;
		}
		i++;
	}
	if ((buff[0] == 'A') && (buff[1] == 'R') && (buff[2] == 'C'))
	{
		lexerSplit(lexer, buff, " \n");
		tmp = lexerGetToken(lexer);/*ARC:*/

		if (!strcmp(tmp, "ARC:"))
		{
			
			x = lexerGetTokenAsInt(lexer);
			y = lexerGetTokenAsInt(lexer);
			z = lexerGetTokenAsInt(lexer);
			/*On ajoute au sommet x un arc vers z de cout y*/
			graphAddArc(dun, x, z, y);
		}
		else
		{
			free(lexer);
			printf("Error in ARC number %d", i);
			return;
		}
	}
	fclose(data->f);
	free(lexer);
}

void		parserDestroy(t_graph dungeon)
{
	dungeon = dungeon;
}